package cn.tedu.lucky.draw.server.service.Impl;

import cn.tedu.lucky.draw.server.common.enums.DrawEnum;
import cn.tedu.lucky.draw.server.common.enums.ErrorEnum;
import cn.tedu.lucky.draw.server.common.handler.DrawException;
import cn.tedu.lucky.draw.server.protrocol.po.ActivityRule;
import cn.tedu.lucky.draw.server.protrocol.po.Rule;
import cn.tedu.lucky.draw.server.repository.ActivityRuleRepository;
import cn.tedu.lucky.draw.server.repository.RuleRepository;
import cn.tedu.lucky.draw.server.service.IActivityRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ActivityRuleServiceImpl implements IActivityRuleService {

    @Autowired
    private ActivityRuleRepository activityRuleRepository;

    @Autowired
    private RuleRepository ruleRepository;

    @Override
    public List<Rule> findRuleByActivityId(Long id) {
        List<ActivityRule> activityRules=activityRuleRepository.findByActivityId(id);
        List<Long> ruleIds = activityRules.stream().map(ActivityRule::getRuleId).collect(Collectors.toList());
        List<Rule> ruleList = ruleRepository.findAllById(ruleIds);
        return ruleList;
    }

    @Override
    public List<Rule> noBindRule(Long id) {
        //获取当前活动已绑定的规则id
        List<ActivityRule> activityRules = activityRuleRepository.findByActivityId(id);
        ArrayList<Long> ecludedIds = new ArrayList<>();
        for (ActivityRule activityRule : activityRules) {
            ecludedIds.add(activityRule.getRuleId());
        }
        //准备一个启用状态
        Integer status = Integer.valueOf(DrawEnum.ENABLE.getCode());

        if (ecludedIds.size()==0){
            //如果ecludedIds是空的，查询所有的规则 状态为启用的活动规则
            return ruleRepository.findByStatusEquals(status);
        }
        //查询不在ecludedIds当中的规则
        return ruleRepository.findByIdNotInAndStatusEquals(ecludedIds,status);
    }

    @Override
    public void saveAll(List<ActivityRule> activityRules) {
        List<ActivityRule> activityRuleList = activityRuleRepository.saveAll(activityRules);
        if (activityRuleList==null){
            throw new DrawException(ErrorEnum.SYSTEM_ERROR);
        }
    }


}
